package demo.module_main.v.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import demo.module_main.R;
import demo.module_main.R2;
import demo.module_main.contract.ISplashContract;
import demo.module_main.net.response.VersionInfo;
import demo.module_main.p.SplashPresenter;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import library.base.mvp.presenter.event.BaseEvent;
import library.base.mvp.v.activity.BaseAppCompatActivity;
import library.common.util.AppUtils;
import library.common.util.CommonDialogUtils;
import library.common.util.DeviceUtils;
import library.common.util.NetworkUtil;
import library.common.util.ToastUtils;
import library.common.util.permission.Permission;
import library.common.util.permission.RxPermissionChecker;
import library.multiple_pictures_selector.MultiPictureSelector;
import library.net.BuildConfig;
import library.router.Router;
import module.common.RouterConfig;
import module.common.share.SharedManager;

import static module.common.share.SharedManager.KEY_IS_FIRST_START_APP;
import static module.common.share.SharedManager.KEY_IS_LOGIN;
import static module.common.share.SharedManager.KEY_VERSION_NAME;

/**
 * @author Created by qiang.hou on 2018/12/4.
 * @version 1.0
 */
public class SplashActivity extends BaseAppCompatActivity<SplashPresenter> implements ISplashContract.IView {

    public static final int PERMISSION_SETTING_FOR_PHONE = 12002;
    public static final int PERMISSION_SETTING_FOR_SD_CARD = 12003;
    public static final int PERMISSION_SETTING_FOR_INSTALL_APP = 12004;
    private static final int[] guides_pics = {R.mipmap.icon_1, R.mipmap.icon_2, R.mipmap.icon_3};

    @BindView(R2.id.guide_viewpager)
    ViewPager guideViewpager;
    ProgressDialog downloadProgress;
    /**
     * check version result
     */
    private VersionInfo versionInfo;

    /**
     * is focus update
     */
    private boolean isForceUpdate = false;

    /**
     * update apk file
     */
    private File updateApk;

    @Override
    protected void initView() {
//        requestPhoneStatePermission();
        MultiPictureSelector.getInstance().getImage(this, "0",4);
    }

    @Override
    protected int returnLayoutId() {
        return R.layout.layout_for_splash_activity;
    }

    @Override
    protected SplashPresenter createPresenter() {
        return new SplashPresenter();
    }

    @Override
    protected boolean needEventBus() {
        return true;
    }

    @Override
    protected void onHandleMessage(BaseEvent event) {
        switch (event.actionTag) {
            case SplashPresenter.ACTION_CHECK_VERSION:
                if (null != event.data && event.data instanceof VersionInfo) {
                    showUpdateTipDialog((VersionInfo) event.data);
                }
                break;
            case SplashPresenter.ACTION_SHOW_SPLASH_CONTENT:
                if (null != event.data) {
                    try {
                        showSplashContent((long) event.data);
                    } catch (Exception e) {
                        showSplashContent(SplashPresenter.DELAY_TIME);
                    }
                }
                break;
            case SplashPresenter.ACTION_UPDATE_PROGRESS_VERSION:
                try {
                    Long[] progress = (Long[]) event.data;
                    if (null != progress && progress.length == 2) {
                        showDownLoadProgress(progress[0], progress[1]);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case SplashPresenter.ACTION_DOWNLOAD_APK:
                updateApk = (File) event.data;
                if (null == updateApk) {
                    showRetryDownloadDialog();
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        requestInstallPermission();
                    } else {
                        AppUtils.installApk(SplashActivity.this, getPackageName() + ".FileProvider", updateApk);
                    }
                }
                break;
            case BaseEvent.ACTION_TAG_RESPONSE_ERROR:
                if (event.data != null) {
                    ToastUtils.showToast(this, event.data.toString(), Toast.LENGTH_SHORT);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PERMISSION_SETTING_FOR_PHONE:
                requestPhoneStatePermission();
                break;
            case PERMISSION_SETTING_FOR_SD_CARD:
                requestSDCardPermission();
                break;
            case PERMISSION_SETTING_FOR_INSTALL_APP:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestInstallPermission();
                }
                break;
        }
    }

    /**
     * download failed ,if retry
     */
    private void showRetryDownloadDialog() {
        CommonDialogUtils.showRetryDialog(
                getSupportFragmentManager(),
                getResources().getString(R.string.text_download_apk_failed),
                new CommonDialogUtils.IOnAlertCallback() {
                    @Override
                    public void onCancel() {
                        if (isForceUpdate) {
                            System.exit(0);
                        } else {
                            startNextActivity();
                        }
                    }

                    @Override
                    public void onOk() {
                        if (null != mPresenter) {
                            isForceUpdate = false;
                            mPresenter.doCheckVersion(BuildConfig.VERSION_NAME, DeviceUtils.getDeviceCode(SplashActivity.this));
                        }
                    }
                });
    }

    /**
     * show download progress bar
     */
    private void showDownLoadProgress(long progress, long total) {
        if (null == downloadProgress || !downloadProgress.isShowing()) {
            downloadProgress = new ProgressDialog(this);
            downloadProgress.setCanceledOnTouchOutside(false);
            downloadProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            downloadProgress.setCancelable(false);
            downloadProgress.setProgress(0);
            downloadProgress.setProgressNumberFormat("%1dM/%2dM");//这里设置的是进度条下面显示的文件大小和下载了多少
            downloadProgress.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.text_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (null != mPresenter) {
                        mPresenter.doCancelDownload();
                    }
                    dialog.dismiss();
                    if (isForceUpdate) {
                        System.exit(0);
                    } else {
                        startNextActivity();
                    }
                }
            });
            downloadProgress.setTitle(R.string.text_downloading);
            downloadProgress.show();
        } else {
            downloadProgress.setMax((int) total);
            downloadProgress.setProgress((int) progress);
        }
    }

    /**
     * show not wifi status alert
     */
    private void showNetTipsDialog() {
        CommonDialogUtils.showAlertDialog(
                getSupportFragmentManager(),
                getResources().getString(R.string.text_wifi_config),
                new CommonDialogUtils.IOnAlertCallback() {
                    @Override
                    public void onCancel() {
                        if (isForceUpdate) {
                            System.exit(0);
                        } else {
                            startNextActivity();
                        }
                    }

                    @Override
                    public void onOk() {
                        requestSDCardPermission();
                    }
                });
    }

    /**
     * show update version dialog
     *
     * @param versionInfo VersionInfo
     */
    private void showUpdateTipDialog(final VersionInfo versionInfo) {
        if (null == versionInfo || null == versionInfo.versionUpdate) {
            return;
        }
        this.versionInfo = versionInfo;
        isForceUpdate = versionInfo.versionUpdate.forceUpdate.equals("1");

        String[] tipsInfo = versionInfo.getTipsInfo();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (null != tipsInfo) {
            builder.setItems(tipsInfo, null);
        }

        builder.setTitle(getString(R.string.text_have_new_version) + versionInfo.versionUpdate.versionName)
                .setPositiveButton(R.string.text_update_version_btn_now, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (NetworkUtil.getNetworkType(SplashActivity.this) == NetworkUtil.NET_TYPE_WIFI) {
                            requestSDCardPermission();
                        } else {
                            showNetTipsDialog();
                        }
                    }
                })
                .setCancelable(true);
        if (isForceUpdate) {
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    System.exit(0);
                }
            });
        } else {
            builder.setNegativeButton(R.string.text_update_version_btn_after, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    startNextActivity();
                }
            });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    startNextActivity();
                }
            });
        }
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * request REQUEST_INSTALL_PACKAGES
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestInstallPermission() {
        new RxPermissionChecker()
                .activity(this)
                .grantCallback(new RxPermissionChecker.IOnPermissionGrant() {
                    @Override
                    public void onPermissionGrant(Permission permission) {
                        AppUtils.installApk(SplashActivity.this, getPackageName() + ".FileProvider", updateApk);
                    }
                })
                .deniedCallback(null)
                .settingActivityRequestCode(PERMISSION_SETTING_FOR_INSTALL_APP)
                .requestPermission(Manifest.permission.REQUEST_INSTALL_PACKAGES);
    }

    /**
     * request PERMISSION_SETTING_FOR_SD_CARD
     */
    private void requestSDCardPermission() {
        new RxPermissionChecker()
                .activity(this)
                .grantCallback(new RxPermissionChecker.IOnPermissionGrant() {
                    @Override
                    public void onPermissionGrant(Permission permission) {
                        if (null != mPresenter && null != versionInfo && null != versionInfo.versionUpdate) {
                            mPresenter.doUpdateVersion(versionInfo.versionUpdate.url);
                        }
                    }
                })
                .deniedCallback(null)
                .onDefaultDeniedDialogCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        if (isForceUpdate) {
                            System.exit(0);
                        } else {
                            startNextActivity();
                        }
                    }
                })
                .settingActivityRequestCode(PERMISSION_SETTING_FOR_SD_CARD)
                .requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * request READ_PHONE_STATE
     */
    private void requestPhoneStatePermission() {
        new RxPermissionChecker()
                .activity(this)
                .grantCallback(new RxPermissionChecker.IOnPermissionGrant() {
                    @Override
                    public void onPermissionGrant(Permission permission) {
                        mPresenter.doCheckVersion(BuildConfig.VERSION_NAME, DeviceUtils.getDeviceCode(SplashActivity.this));
                    }
                })
                .deniedCallback(null)
                .settingActivityRequestCode(PERMISSION_SETTING_FOR_PHONE)
                .requestPermission(Manifest.permission.READ_PHONE_STATE);
    }

    /**
     * show guides or jump to next activity
     */
    @SuppressLint("CheckResult")
    private void showSplashContent(long delay) {
        if (SharedManager.getInstance().getValue(SharedManager.KEY_IS_FIRST_START_APP, true)) {
            showGuide();
        } else {
            if (delay > 0) {
                Observable.timer(delay, TimeUnit.MILLISECONDS)
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) {
                                startNextActivity();
                            }
                        });
            } else {
                startNextActivity();
            }
        }
    }

    /**
     * show guide pictures
     */
    private void showGuide() {
        SharedManager.getInstance().setValue(KEY_IS_FIRST_START_APP, false);
        final List<View> views = new ArrayList<>();
        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        for (int pic : guides_pics) {
            ImageView iv = new ImageView(this);
            iv.setLayoutParams(mParams);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            iv.setImageResource(pic);
            views.add(iv);
        }
        views.get(views.size() - 1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 最后一张图片点击直接进入系统
                String versionInfo = BuildConfig.VERSION_NAME;
                SharedManager.getInstance().setValue(KEY_VERSION_NAME, versionInfo);
                startNextActivity();
            }
        });

        //设置adapter
        guideViewpager.setVisibility(View.VISIBLE);
        guideViewpager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return views.size();
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                container.addView(views.get(position));
                return views.get(position);
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(views.get(position));
            }

            @Override
            public boolean isViewFromObject(@NonNull View arg0, @NonNull Object arg1) {
                return arg0 == arg1;
            }
        });
    }

    /**
     * goto login or main page
     */
    private void startNextActivity() {
        // 检查用户注册状态
        if (!SharedManager.getInstance().getValue(KEY_IS_LOGIN, false)) {
            Router.getInstance().startActivity(RouterConfig.login_LoginActivity);
        } else {
            Intent intent = new Intent(SplashActivity.this, AppBottomBarViewPagerActivity.class);
            startNextActivity(intent,
                    false,
                    0,
                    R.anim.slide_right_in,
                    R.anim.slide_right_out, true);
        }
        finish();
    }
}
